package com.example.xinyun.slice;

import com.example.xinyun.MyApplication;
import com.example.xinyun.ResourceTable;
import com.example.xinyun.domain.UrlContant;
import com.example.xinyun.db.User;
import com.example.xinyun.db.db_User;
import com.example.xinyun.domain.convert;
import com.google.gson.Gson;
import com.zzrv5.mylibrary.ZZRCallBack;
import com.zzrv5.mylibrary.ZZRHttp;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.window.dialog.ToastDialog;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;

public class SettingSlice extends AbilitySlice {
    final int imgRequestCode=1123;
    Image img;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_setting);
        Image ret=(Image)findComponentById(ResourceTable.Id_return_img);
        img = (Image)findComponentById(ResourceTable.Id_img);
        DirectionalLayout setImage = (DirectionalLayout) findComponentById(ResourceTable.Id_setting_userImage);
        DirectionalLayout updataPassword = (DirectionalLayout) findComponentById(ResourceTable.Id_updata_Password);
        Image return_img = (Image) findComponentById(ResourceTable.Id_return_img);
        return_img.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent=new Intent();
                //页面跳转
                present(new HomeFraction(),intent);
            }
        });
        if (MyApplication.user_Image==null)
        {
            img.setPixelMap(ResourceTable.Media_userImage);
        }else {
            img.setPixelMap(convert.ByteToPixelMap(MyApplication.user_Image));
        }
        setImage.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                //修改用户头像
                requestPermissionsFromUser(new String[]{"ohos.permission.READ_USER_STORAGE"},imgRequestCode);
                selectPic();
            }
        });
        updataPassword.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent=new Intent();
                //页面跳转
                present(new ChangePasswordSlice(),intent);
            }
        });
        ret.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent=new Intent();
                //页面跳转
                present(new HomeFraction(),intent);
            }
        });

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
    public void selectPic(){
        Intent intent = new Intent();
        Operation opt=new Intent.OperationBuilder().withAction("android.intent.action.GET_CONTENT").build();
        intent.setOperation(opt);
        intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
        intent.setType("image/*");
        startAbilityForResult(intent, imgRequestCode);
    }
    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {

        if(requestCode==imgRequestCode)
        {
            //选择的Img对应的Uri
            String chooseImgUri=resultData.getUriString();
            //定义数据能力帮助对象
            DataAbilityHelper helper=DataAbilityHelper.creator(getContext());
            //定义图片来源对象
            ImageSource imageSource = null;
            //获取选择的Img对应的Id
            String chooseImgId=null;
            //如果是选择文件则getUriString结果为content://com.android.providers.media.documents/document/image%3A30，其中%3A是":"的URL编码结果，后面的数字就是image对应的Id
            //如果选择的是图库则getUriString结果为content://media/external/images/media/30，最后就是image对应的Id
            //这里需要判断是选择了文件还是图库
            if(chooseImgUri.lastIndexOf("%3A")!=-1){
                chooseImgId = chooseImgUri.substring(chooseImgUri.lastIndexOf("%3A")+3);
            }
            else {
                chooseImgId = chooseImgUri.substring(chooseImgUri.lastIndexOf('/')+1);
            }
            //获取图片对应的uri，由于获取到的前缀是content，我们替换成对应的dataability前缀
            Uri uri=Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,chooseImgId);
            try {
                //读取图片
                FileDescriptor fd = helper.openFile(uri, "r");
                imageSource = ImageSource.create(fd, null);
                //创建位图
                PixelMap pixelMap = imageSource.createPixelmap(null);
                img.setPixelMap(pixelMap);
                User user=new User(MyApplication.username,null, convert.PixelMapToBytes(pixelMap));
                ZZRHttp.postJson(UrlContant.URL+"updateUser", user.updataImage(), new ZZRCallBack.CallBackString() {
                    @Override
                    public void onFailure(int i, String s) {
                        new ToastDialog(getContext())
                                .setText("网络连接失败！")
                                .show();
                    }

                    @Override
                    public void onResponse(String s) {
                        db_User db_user = new Gson().fromJson(s, db_User.class);
                        if (db_user.getCode().equals("200"))
                        {
                            MyApplication.user_Image=convert.PixelMapToBytes(pixelMap);
                        }
                        else {
                            new ToastDialog(getContext())
                                    .setText("用户头像更新失败")
                                    .show();
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (imageSource != null) {
                    imageSource.release();
                }
            }
        }
    }

}
